package com.grademaster.service.impl;


import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.grademaster.common.R;
import com.grademaster.dto.UserDto;
import com.grademaster.dto.UserPageDto;
import com.grademaster.entity.LoginRecords;
import com.grademaster.entity.Role;
import com.grademaster.entity.StudentInfo;
import com.grademaster.entity.User;
import com.grademaster.mapper.UserMapper;
import com.grademaster.service.LoginRecordsService;
import com.grademaster.service.RoleService;
import com.grademaster.service.StudentInfoService;
import com.grademaster.service.UserService;
import com.grademaster.util.IpUtils;
import com.grademaster.util.LoginUtil;
import com.grademaster.util.StringUtils;
import com.grademaster.vo.UserVO;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.tomcat.util.http.fileupload.ByteArrayOutputStream;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @author Administrator
 * @description 针对表【user】的数据库操作Service实现
 * @createDate 2024-06-24 20:32:54
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Autowired
    private RoleService roleService;
    @Autowired
    private StudentInfoService studentInfoService;
    @Autowired
    private LoginRecordsService loginRecordsService;
    @Autowired
    private UserMapper userMapper;

    /**
     * 用户登录
     *
     * @param userDto
     * @return
     */
    @Override
    public R login(UserDto userDto) {
        // 查询数据库
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, userDto.getUsername());
        User user = this.getOne(queryWrapper);
        //判断用户是否存在
        if (user == null) {
            return R.error("用户不存在");
        }
        //判断用户密码是否正确
        if (!user.getPassword().equals(userDto.getPassword())) {
            return R.error("密码错误");
        }
        //判断用户状态是否可用
        if (user.getStatus() == 0) {
            return R.error("用户不可用");
        }
        //sa-token 登录 角色id+用户id
        StpUtil.login(user.getRoleId()+":"+user.getId());
        //登录成功，记录登录日志
        LoginRecords loginRecords = new LoginRecords();
        loginRecords.setUserId(user.getId());
        loginRecords.setRoleId(user.getRoleId());
        loginRecords.setDevice(IpUtils.getHostName());
        loginRecords.setIpAddress(IpUtils.getHostIp());
        loginRecords.setTime(new Date(System.currentTimeMillis()));
        loginRecords.setStatus(0);
        loginRecordsService.save(loginRecords);
        return R.success(StpUtil.getTokenInfo().getTokenValue());
    }

    /**
     * 获取用户权限信息
     *
     * @return
     */
    @Override
    public R getPermissions() {
        //根据角色id查询权限信息
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Role::getId, LoginUtil.getLoginRoleId());
        Role role = roleService.getOne(queryWrapper);
        return R.success(role);
    }

    /**
     * 用户退出登录
     *
     * @return
     */
    @Override
    public R logout() {
        //用户退出，记录退出日志
        LoginRecords loginRecords = new LoginRecords();
        loginRecords.setUserId(Long.valueOf(LoginUtil.getLoginUserId()));
        loginRecords.setRoleId(Long.valueOf(LoginUtil.getLoginRoleId()));
        loginRecords.setDevice(IpUtils.getHostName());
        loginRecords.setIpAddress(IpUtils.getHostIp());
        loginRecords.setTime(new Date(System.currentTimeMillis()));
        loginRecords.setStatus(1);
        loginRecordsService.save(loginRecords);
        StpUtil.logout();
        return R.success("退出登录成功");
    }


    /**
     * 获取所有用户，分页
     *
     * @param userPageDto
     * @return
     */
    @Override
    public R getAllUsersByPage(UserPageDto userPageDto) {
        StpUtil.isLogin();
        //既不是成绩管理员也不是管理员
        if (!LoginUtil.isAdmin()){
            return R.error("权限不足");
        }

        Page<User> page = new Page<>(userPageDto.getPage(), userPageDto.getPageSize());

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        //判断是否有查询
        queryWrapper.like(StringUtils.isNotEmpty(userPageDto.getUsername()), User::getUsername, userPageDto.getUsername());

        queryWrapper.like(StringUtils.isNotEmpty(userPageDto.getName()), User::getName, userPageDto.getName());

        queryWrapper.eq(userPageDto.getRoleId()!=null,User::getRoleId, userPageDto.getRoleId());

        queryWrapper.eq(userPageDto.getStatus()!=null,User::getStatus, userPageDto.getStatus());

        return R.success(this.page(page,queryWrapper));
    }
    /**
     * 导出用户信息
     *
     * @param userPageDto
     * @return
     */
    @Override
    public ResponseEntity exportExcel(UserPageDto userPageDto) {
        StpUtil.isLogin();
        //既不是成绩管理员也不是管理员
        if (!LoginUtil.isAdmin()){
            return ResponseEntity.badRequest().build();
        }

        Page<User> page = new Page<>(1, 2000);

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        //判断是否有查询
        queryWrapper.like(StringUtils.isNotEmpty(userPageDto.getUsername()), User::getUsername, userPageDto.getUsername());

        queryWrapper.like(StringUtils.isNotEmpty(userPageDto.getName()), User::getName, userPageDto.getName());

        queryWrapper.eq(userPageDto.getRoleId()!=null,User::getRoleId, userPageDto.getRoleId());

        queryWrapper.eq(userPageDto.getStatus()!=null,User::getStatus, userPageDto.getStatus());
        Page<User> page1 = this.page(page, queryWrapper);
        List<User> records = page1.getRecords();

        Workbook workbook = new XSSFWorkbook();

        // Create a sheet named "Users"
        Sheet sheet = workbook.createSheet("Users");

        // Create header row
        Row headerRow = sheet.createRow(0);
        String[] headers = {"用户ID", "用户名", "姓名", "角色ID", "状态"};
        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
        }

        // Create data rows
        int rowNum = 1;
        for (User user : records) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(user.getId());
            row.createCell(1).setCellValue(user.getUsername());
            row.createCell(2).setCellValue(user.getName());
            row.createCell(3).setCellValue(user.getRoleId());
            row.createCell(4).setCellValue(user.getStatus());
        }

        // Auto-size columns (optional)
        for (int i = 0; i < headers.length; i++) {
            sheet.autoSizeColumn(i);
        }

        // Write workbook to ByteArrayOutputStream
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // Create InputStreamResource to wrap ByteArrayInputStream
        ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
        InputStreamResource resource = new InputStreamResource(inputStream);

        // Set response headers
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=users.xlsx");

        // Return ResponseEntity with Excel file as body
        return ResponseEntity.ok()
                .headers(httpHeaders)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    }

    /**
     * 添加或编辑用户
     *
     * @param user
     * @return
     */
    @Override
    public R addOrEditUser(User user) {
        StpUtil.isLogin();
        //既不是成绩管理员也不是管理员
        if (!LoginUtil.isAdmin()){
            return R.error("权限不足");
        }
        if (user.getId()!=null){
            //修改用户
            return R.success(this.updateById(user));
        }
        this.save(user);
        if (user.getRoleId() == 3L){
            //是学生加上学生信息表
            StudentInfo studentInfo = new StudentInfo();
            studentInfo.setStudentId(user.getId());
            studentInfo.setClassId(10L);
            studentInfoService.save(studentInfo);
        }
        //添加用户
        return R.success("添加成功");
    }

    /**
     * 删除用户
     *
     * @param userId
     * @return
     */
    @Override
    public R deleteUser(String userId) {
        StpUtil.isLogin();
        //既不是成绩管理员也不是管理员
        if (!LoginUtil.isAdmin()){
            return R.error("权限不足");
        }
        String[] ids = userId.split(",");
        for (String id : ids) {
            this.removeById(id);
        }
        return R.success("删除成功");
    }

    /**
     * 获取所有教师
     *
     * @return
     */
    @Override
    public R getAllTeachers() {
        StpUtil.isLogin();
        //既不是成绩管理员也不是管理员
        if (!LoginUtil.isAdmin()){
            return R.error("权限不足");
        }

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(User::getRoleId, 4L);
        return R.success(this.list(queryWrapper));
    }

    /**
     * 获取用户个人信息
     *
     * @return
     */
    @Override
    public R getUserInfo() {
        StpUtil.isLogin();

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getId, LoginUtil.getLoginUserId());
        User user = this.getOne(queryWrapper);

        if(LoginUtil.getLoginRoleId().equals("3")){
            //是学生需要多加数据
            UserVO uservo = userMapper.getUserDetails(user.getId());
            return R.success(uservo);
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return R.success(userVO);
    }

    /**
     * 修改用户密码
     *
     * @param password
     * @return
     */
    @Override
    public R changePassword(String password) {
        StpUtil.isLogin();

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(User::getId, LoginUtil.getLoginUserId());

        User user = this.getOne(queryWrapper);

        user.setPassword(password);

        this.updateById(user);

        return R.success("修改成功");
    }



}




